<template>
  <div class="table-page">
    <a-form label-align="right" auto-label-width :model="form" class="form">
      <a-row :gutter="16" wrap>
        <a-col :xs="12" :md="12" :lg="8" :xl="6" :xxl="6">
          <a-form-item field="nickname" label="用户信息">
            <a-input v-model="form.nickname" placeholder="请输入用户昵称" />
          </a-form-item>
        </a-col>
        <a-col :xs="12" :md="12" :lg="8" :xl="6" :xxl="6">
          <a-form-item field="mobile" label="用户手机号">
            <a-input v-model="form.mobile" placeholder="请输入手机号码" />
          </a-form-item>
        </a-col>
        <a-col :xs="12" :md="12" :lg="8" :xl="6" :xxl="6">
          <a-form-item field="rangeValue" label="交稿时间">
            <a-range-picker v-model="form.rangeValue" />
          </a-form-item>
        </a-col>
        <a-col :xs="12" :md="12" :lg="8" :xl="6" :xxl="6">
          <a-form-item field="keyword_id" label="任务编号">
            <a-input v-model="form.keyword_id" placeholder="请输入任务编号" />
          </a-form-item>
        </a-col>
        <a-col :xs="12" :md="12" :lg="8" :xl="6" :xxl="6">
          <a-form-item field="demand_name" label="需求名称">
            <a-input v-model="form.demand_name" placeholder="请输入需求名称" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-space>
            <a-button
              type="primary"
              @click="
                () => {
                  activeName = '0,1,2,3,4,5,6,7,8'
                  getTableData()
                }
              "
            >
              <template #icon>
                <icon-search />
              </template>
              <template #default>查询</template>
            </a-button>
            <a-button @click="handleReset">
              <template #default>重置</template>
            </a-button>
          </a-space>
        </a-col>
      </a-row>
    </a-form>
    <div class="tab-content">
      <a-tabs @change="handleClick" v-model="activeName" default-active-key="0,1,2,3,4,5,6,7,8">
        <a-tab-pane v-for="item in tabList" :key="item.value">
          <template #title>
            <a-badge
              :dot-style="{ height: '16px', minWidth: '16px', lineHeight: '16px', top: '-2px', right: '-2px' }"
              size="small"
              :count="item.num"
            >
              {{ item.name }}</a-badge
            >
          </template>
        </a-tab-pane>
      </a-tabs>
    </div>

    <section class="table-box">
      <a-table
        row-key="id"
        size="small"
        page-position="bl"
        :bordered="{ cell: true }"
        :loading="loading"
        :data="tableData"
        :scroll="{ x: '100%', y: '100%', minWidth: 1000 }"
        :pagination="{ showPageSize: true, showTotal: true, total: total, current: current, pageSize: pageSize }"
        @page-change="changeCurrent"
        @page-size-change="changePageSize"
      >
        <template #columns>
          <a-table-column title="任务编号" data-index="id" :width="110">
            <template #cell="{ record }">
              <span>{{ padNumber(record.id, 4) }}</span>
            </template>
          </a-table-column>
          <a-table-column title="用户信息" :min-width="220" data-index="nickname">
            <template #cell="{ record }">
              <span>{{
                record.Customer?.nickname +
                ' - ' +
                record.Customer?.mobile?.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2')
              }}</span>
            </template></a-table-column
          >
          <a-table-column title="任务状态" :width="120" data-index="status">
            <template #cell="{ record }">
              {{ statusMap[record.status] }}
            </template>
          </a-table-column>
          <a-table-column title="创建时间" :width="180" data-index="create_time"></a-table-column>
          <a-table-column title="交稿时间" :width="180" data-index="deliveryTime">
            <template #cell="{ record }">
              {{ record.end_time ? format(record.end_time * 1000, 'yyyy-MM-dd') : record.end_time }}
            </template>
          </a-table-column>
          <a-table-column title="所属需求" :min-width="200" data-index="demandName">
            <template #cell="{ record }">
              {{ record.DemandList?.name }}
            </template>
          </a-table-column>
          <a-table-column title="操作" fixed="right" :width="250" align="center">
            <template #cell="{ record }">
              <a-space :size="4">
                <a-link v-if="record.status == 2" size="small" @click="handleViewKeyword(record, 'view')">
                  <template #default>查看关键词</template>
                </a-link>
                <a-link
                  status="warning"
                  v-if="record.status == 1"
                  size="small"
                  @click="handleViewKeyword(record, 'audit')"
                >
                  <template #default>审核关键词</template>
                </a-link>
                <a-link
                  v-if="record.status == 5 || record.status == 4 || record.status == 8"
                  size="small"
                  @click="hnadleOpenApprove('view', record.id)"
                >
                  <template #default>查看</template>
                </a-link>
                <a-link
                  status="warning"
                  v-if="record.status == 3 || record.status == 6 || record.status == 7"
                  size="small"
                  @click="hnadleOpenApprove('edit', record.id)"
                >
                  <template #default>去撰写</template>
                </a-link>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </section>
    <keywordApprove
      @handleSuccess="handleSuccess"
      ref="keywordApproveRef"
      :num="keywordModalInfo.num"
      :type="keywordModalInfo.type"
      :taskId="keywordModalInfo.taskId"
      :taskStatus="keywordModalInfo.taskStatus"
    ></keywordApprove>
  </div>
</template>

<script setup lang="ts" name="MainTable">
import { reactive, ref } from 'vue'
import { usePagination } from '@/hooks'
import { getMyTaskList, deleteDemandList } from '@/apis'
import { useRouter } from 'vue-router'
import { Message } from '@arco-design/web-vue'
import { format } from 'date-fns'
import keywordApprove from './components/keywordApprove.vue'

const keywordApproveRef = ref(null)
const keywordModalInfo = ref({
  num: '',
  type: '',
  taskId: ''
})
const router = useRouter()
const form = reactive({
  mobile: '',
  nickname: '',
  rangeValue: [],
  keyword_id: '',
  demand_name: ''
})
const tabList = ref([
  {
    name: '待撰写',
    value: '3,6,7',
    num: 0
  },
  {
    name: '待关键词审核',
    value: '1',
    num: 0
  },
  {
    name: '待审核稿件',
    value: '4',
    num: 0
  },
  {
    name: '待确认稿件',
    value: '5',
    num: 0
  },
  {
    name: '待修改关键词',
    value: '2',
    num: 0
  },
  {
    name: '已取消',
    value: '0',
    num: 0
  },
  {
    name: '已完成',
    value: '8',
    num: 0
  },
  {
    name: '全部',
    value: '0,1,2,3,4,5,6,7,8',
    num: 0
  }
])
const activeName = ref('0,1,2,3,4,5,6,7,8')
const statusMap = {
  1: '待审核关键词',
  2: '关键词审核不通过',
  3: '待小编撰写',
  4: '待主管审核稿件',
  5: '待用户确认稿件',
  6: '主管驳回待小编撰写',
  7: '用户驳回待小编撰写',
  8: '已完成',
  0: '已取消'
}
const loading = ref(false)
const tableData = ref([])

const { current, pageSize, total, changeCurrent, changePageSize, setTotal } = usePagination(() => getTableData())

const handleClick = (tab) => {
  activeName.value = tab
  getTableData()
}
const getTableData = async (type) => {
  loading.value = true
  const where = {
    page: current.value,
    num: pageSize.value,
    ...form,
    status_in: activeName.value,
    admin_pc: 1
  }
  if (form.rangeValue.length > 0) {
    where.end_start_time = format(form.rangeValue[0], 'yyyy-MM-dd 00:00:00')
    where.end_end_time = format(form.rangeValue[1], 'yyyy-MM-dd 23:59:59')
  }
  if (type) {
    where.status_in = type
  }
  if (form.keyword_id) {
    where.keyword_id = form.keyword_id.replace(/^0+/, '')
  }
  const res = await getMyTaskList(where)
  let resData = JSON.parse(res)
  if (type == '3,6,7' || activeName.value == '3,6,7') {
    tabList.value[0].num = resData.result?.total || 0
  }
  if (type == '1' || activeName.value == '1') {
    tabList.value[1].num = resData.result?.total || 0
  }
  if (type) {
    return
  }
  if (resData.code === 200) {
    tableData.value = (resData.result.data || []).reverse().map((dd) => {
      let start_time = dd.start_time === '9999999999' ? '长期' : format(dd.start_time * 1000, 'yyyy-MM-dd')
      let end_time = dd.end_time === '9999999999' ? '长期' : format(dd.end_time * 1000, 'yyyy-MM-dd')
      let time = ''
      if (dd.repeat == 2) {
        time = end_time
      }
      if (dd.repeat == 1) {
        time = type_map[dd.type]
      }
      return {
        ...dd,
        expiryDate: start_time + ' ~ ' + end_time,
        time
      }
    })
    setTotal(resData.result.total)
    loading.value = false
  } else {
    loading.value = false
  }
}
const handleReset = () => {
  form.mobile = ''
  form.nickname = ''
  form.rangeValue = []
  form.keyword_id = ''
  form.demand_name = ''
  getTableData()
}
const handleDelete = (record) => {
  deleteDemandList({
    demand_id: record.id
  }).then((res) => {
    const resData = JSON.parse(res)
    if (resData.code === 200) {
      Message.success('删除成功')
      getTableData()
    } else {
      Message.error('删除失败')
    }
  })
}
const padNumber = (num, size) => {
  // 将数字转换为字符串
  let numStr = num.toString()
  // 计算需要补齐的位数
  let diff = size - numStr.length
  // 如果需要补齐，则在数字前面添加相应数量的0
  if (diff > 0) {
    // 使用 Array 方法填充0，并拼接原始数字字符串
    numStr = '0'.repeat(diff) + numStr
  }
  return numStr
}
const handleViewKeyword = (row, type) => {
  keywordModalInfo.value.num = row.manuscripts_num
  keywordModalInfo.value.taskId = row.id
  keywordModalInfo.value.type = type
  keywordModalInfo.value.taskStatus = row.status
  nextTick(() => {
    keywordApproveRef.value.show()
  })
}
const handleSuccess = () => {
  getTableData()
  getTableData('3,6,7')
  getTableData('1')
}
handleSuccess()
// 跳转审核、查看页面
const hnadleOpenApprove = (type, id) => {
  router.push({ path: '/task-center/approveTask', query: { type, id } })
}
</script>

<style lang="scss" scoped>
:deep(.arco-grid) {
  flex-wrap: wrap;
}
:deep(.arco-grid-item) {
  min-width: 250px;
}
:deep(.arco-alert-success) {
  padding: 14px 16px;
  border-color: rgb(var(--success-6));
  background-color: rgba(var(--success-6), 0.08);
  .arco-alert-content {
    color: rgb(var(--success-6));
    font-size: 12px;
  }
}
.table-page {
  height: 100%;
  overflow: hidden;
  margin: $margin;
  background: var(--color-bg-1);
  padding: $padding;
  padding-bottom: 0;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  .form {
    margin-top: 12px;
    :deep(.arco-form-item) {
      margin-bottom: 10px;
    }
  }
  .table-box {
    flex: 1;
    overflow: hidden;
    margin-top: 12px;
    padding-bottom: 16px;
  }
}
</style>
